//
//  NotificationCenterViewController.swift
//  TJJPT
//
//  Created by FENGYL on 2017/6/29.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

import UIKit
import MJRefresh
import SVProgressHUD

class NotificationCenterViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    enum NotificationType:Int {
        case all
        case wakeUp
        case current
    }

    @IBOutlet weak var notificationTableView: UITableView!
    
    var blackBackgroudView:UIView?
    var datePicker:UIDatePicker?
    var selectDate = Date.init()
    
    var notificationType:NotificationType = .all
    
    var noDataLabel = UILabel.init()
    
    
   
    
    var alertArray:[HistoryEventDataByTime?] = []
    var backupAlertArray:[HistoryEventDataByTime?] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setUpView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - 初始化
    func setUpView() {
        
        // MARK: 设置标题
        self.title = NSLocalizedString(LOCALIZABLE_STRING_NOTIFICATION_CENTER, comment: "")
        
        // MARK: NoData Label
        noDataLabel.frame = CGRect(x: 0, y: 0, width: 80, height: 20)
        noDataLabel.center = notificationTableView.center
        noDataLabel.text = "No Data."
        noDataLabel.textColor = UIColor.gray
        
        // MARK: TableView
        self.notificationTableView.tableFooterView = UIView.init()
        
        self.notificationTableView.delegate = self
        self.notificationTableView.dataSource = self
        
        self.notificationTableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            
            self.refreshNotification()
            
        })
        
        self.notificationTableView.mj_header.beginRefreshing()
        
    }
    
    // MARK: - 刷新通知
    func refreshNotification() {
        
        switch notificationType {
        case .all:
            
            // MARK: 全部刷新
            if UserModel.userModel.devicesByAccountArray != nil {
                
                if (UserModel.userModel.devicesByAccountArray?.count)! > 0 {
                    
                    var index = 0
                    
                    self.alertArray.removeAll()
                    
                    var a:[HistoryEventDataByTime?] = []
                    
                    for dict in UserModel.userModel.devicesByAccountArray! {
                        
                        let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
                        
                        NetworkCommand.getHistoryEventDataByTime(selectDate: selectDate, serialNumber: devicesByAccount?.SerialNumber, id: nil, clientType: nil, tokenPass: nil, success: { (response) in
                            
                            if response as? NSArray != nil {
                                
                                let r:NSArray = response as! NSArray
                                
                                if r.count > 0 {

                                    for dict in r {
                                        
                                        let historyEventDataByTime = HistoryEventDataByTime.mj_object(withKeyValues: dict)
                                        
                                        if historyEventDataByTime != nil {
                                            
                                            if historyEventDataByTime?.EventTime != nil {
                                                
                                                a.append(historyEventDataByTime)
                                                
                                                if historyEventDataByTime?.AlarmType != 21 && historyEventDataByTime?.AlarmType != 28 && historyEventDataByTime?.AlarmType != 48 {
                                                    
                                                    self.alertArray.append(historyEventDataByTime)
                                                    
                                                }

                                            }
                                            
                                            if index == (UserModel.userModel.devicesByAccountArray?.count)! - 1 {
                                                
                                                self.sortAlertArray()
                                                
                                                self.backupAlertArray = a
                                                
                                                self.notificationTableView.reloadData()
                                                
                                            }
                                            
                                        }
                                        
                                    }
                                    
                                }
                                
                            }
                            
                            
                            
                            
                            
                            if index == (UserModel.userModel.devicesByAccountArray?.count)! - 1 {
                                
                                self.notificationTableView.mj_header.endRefreshing()
                                
                            }
                            
                            index += 1
                            
                            
                        }, failure: { (Error) in
                            
                            if index == (UserModel.userModel.devicesByAccountArray?.count)! - 1 {
                                
                                self.notificationTableView.mj_header.endRefreshing()
                                
                            }
                            
                            SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_FAILURE, comment: ""))
                            SVProgressHUD.dismiss(withDelay: 1)
                            
                            index += 1
                            
                        })
                        
                        
                    }
                    
                }
                
            }
            
            break
            
        case .wakeUp:
            
            // MARK: 唤醒
            if UserModel.userModel.devicesByAccountArray != nil {
                
                if (UserModel.userModel.devicesByAccountArray?.count)! > 0 {
                    
                    var index = 0
                    
                    self.alertArray.removeAll()
                    
                    var a:[HistoryEventDataByTime?] = []
                    
                    for dict in UserModel.userModel.devicesByAccountArray! {
                        
                        let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
                        
                        NetworkCommand.getHistoryEventDataByTime(selectDate: selectDate, serialNumber: devicesByAccount?.SerialNumber, id: nil, clientType: nil, tokenPass: nil, success: { (response) in
                            
                            if response as? NSArray != nil {
                                
                                let r:NSArray = response as! NSArray
                                
                                if r.count > 0 {

                                    for dict in r {
                                        
                                        let historyEventDataByTime = HistoryEventDataByTime.mj_object(withKeyValues: dict)
                                        
                                        if historyEventDataByTime != nil {
                                            
                                            if historyEventDataByTime?.EventTime != nil {
                                                
                                                a.append(historyEventDataByTime)
                                                
                                                if historyEventDataByTime?.AlarmType != 21 && historyEventDataByTime?.AlarmType != 28 && historyEventDataByTime?.AlarmType != 48 {
                                                    
                                                    self.alertArray.append(historyEventDataByTime)
                                                    
                                                }
                                                
                                            }
                                            
                                            if index == (UserModel.userModel.devicesByAccountArray?.count)! - 1 {
                                                
                                                self.sortAlertArray()
                                                
                                                self.backupAlertArray = a
                                                
                                                self.notificationTableView.reloadData()
                                                
                                            }
                                            
                                        }
                                        
                                    }
                                    
                                }
                                
                            }
                            
                            
                            
                            
                            
                            if index == (UserModel.userModel.devicesByAccountArray?.count)! - 1 {
                                
                                self.notificationTableView.mj_header.endRefreshing()
                                
                            }
                            
                            index += 1
                            
                            
                        }, failure: { (Error) in
                            
                            if index == (UserModel.userModel.devicesByAccountArray?.count)! - 1 {
                                
                                self.notificationTableView.mj_header.endRefreshing()
                                
                            }
                            
                            SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_FAILURE, comment: ""))
                            SVProgressHUD.dismiss(withDelay: 1)
                            
                            index += 1
                            
                        })
                        
                        
                    }
                    
                }
                
            }
            
            
            break
            
        case .current:
            
            if UserModel.userModel.devicesByAccountArray != nil {
                
                if (UserModel.userModel.devicesByAccountArray?.count)! > 0 {
                    
                    var index = 0
                    
                    self.alertArray.removeAll()
                    
                    var a:[HistoryEventDataByTime?] = []
                    
                    for dict in UserModel.userModel.devicesByAccountArray! {
                        
                        let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
                        
                        NetworkCommand.getHistoryEventDataByTime(selectDate: selectDate, serialNumber: devicesByAccount?.SerialNumber, id: nil, clientType: nil, tokenPass: nil, success: { (response) in
                            
                            if response as? NSArray != nil {
                                
                                let r:NSArray = response as! NSArray
                                
                                if r.count > 0 {
                                    
                                    for dict in r {
                                        
                                        let historyEventDataByTime = HistoryEventDataByTime.mj_object(withKeyValues: dict)
                                        
                                        if historyEventDataByTime != nil {
                                            
                                            if historyEventDataByTime?.EventTime != nil {
                                                
                                                a.append(historyEventDataByTime)
                                                
                                                if historyEventDataByTime?.AlarmType != 21 && historyEventDataByTime?.AlarmType != 28 && historyEventDataByTime?.AlarmType != 48 && historyEventDataByTime?.SerialNumber == UserModel.userModel.selectedDeviceSerialNumber {
                                                    
                                                    self.alertArray.append(historyEventDataByTime)
                                                    
                                                }
                                                
                                            }
                                            
                                            if index == (UserModel.userModel.devicesByAccountArray?.count)! - 1 {
                                                
                                                self.sortAlertArray()
                                                
                                                self.backupAlertArray = a
                                                
                                                self.notificationTableView.reloadData()
                                                
                                            }
                                            
                                        }
                                        
                                    }
                                    
                                }
                                
                            }
                            
                            
                            
                            
                            
                            if index == (UserModel.userModel.devicesByAccountArray?.count)! - 1 {
                                
                                self.notificationTableView.mj_header.endRefreshing()
                                
                            }
                            
                            index += 1
                            
                            
                        }, failure: { (Error) in
                            
                            if index == (UserModel.userModel.devicesByAccountArray?.count)! - 1 {
                                
                                self.notificationTableView.mj_header.endRefreshing()
                                
                            }
                            
                            SVProgressHUD.showError(withStatus: NSLocalizedString(LOCALIZABLE_STRING_FAILURE, comment: ""))
                            SVProgressHUD.dismiss(withDelay: 1)
                            
                            index += 1
                            
                        })
                        
                        
                    }
                    
                }
                
            }
            
            break
            
//        default:
//            break
        }
        
    }
    
    
    // MARK: - alertArray排序
    func sortAlertArray() {

        if alertArray.count > 1 {
            
            for x in 1...alertArray.count-1 {
                for i in 0..<alertArray.count - x{
                    if (alertArray[i]?.EventTime?.intValue)! < (alertArray[i+1]?.EventTime?.intValue)! {
                        let tmp = alertArray[i]
                        alertArray[i] = alertArray[i+1]
                        alertArray[i+1] = tmp
                    }
                }
            }

        }
        
    }
    
    // MARK: - backupAlertArray排序
    func sortBackupAlertArray() {
        
        if backupAlertArray.count > 1 {
            
            for x in 1...backupAlertArray.count-1 {
                for i in 0..<backupAlertArray.count - x{
                    if (backupAlertArray[i]?.EventTime?.intValue)! < (backupAlertArray[i+1]?.EventTime?.intValue)! {
                        let tmp = backupAlertArray[i]
                        backupAlertArray[i] = backupAlertArray[i+1]
                        backupAlertArray[i+1] = tmp
                    }
                }
            }
 
        }
        
    }
    
    // MARK: - 选择显示内容
    @IBAction func selectDisplayNotification(_ sender: Any) {
        
        let alertController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        let onlyCheckWakeUp = UIAlertAction.init(title: NSLocalizedString(LOCALIZABLE_STRING_ONLY_CHECK_WAKE_UP, comment: ""), style: .default) { (UIAlertAction) in
            
//            self.notificationType = .wakeUp
//            
//            self.notificationTableView.mj_header.beginRefreshing()
            
            self.alertArray.removeAll()
            
            if self.backupAlertArray.count > 0 {
                
                self.sortBackupAlertArray()
                
                for h in self.backupAlertArray {
                    
                    if h?.AlarmType != 48 && h?.AlarmType != 28 && h?.AlarmType != 21 {
                        
                        self.alertArray.append(h)
                        
                    }
                    
                }
                
            }
            
            self.notificationTableView.reloadData()
            
            
        }
        
        let checkAllNotification = UIAlertAction.init(title: NSLocalizedString(LOCALIZABLE_STRING_CHECK_ALL_NOTIFICATION, comment: ""), style: .default) { (UIAlertAction) in
            
//            self.notificationType = .all
//            
//            self.notificationTableView.mj_header.beginRefreshing()
            
            self.alertArray.removeAll()
            
            if self.backupAlertArray.count > 0 {
                
                self.sortBackupAlertArray()
                
                for i in 0...(self.backupAlertArray.count - 1) {
                    
                    let h = self.backupAlertArray[i]
                    
                    if h?.AlarmType != 48 && h?.AlarmType != 28 && h?.AlarmType != 21 {
                        
                        self.alertArray.append(h)
                        
                    }
                    
                }
                
            }
            
            self.notificationTableView.reloadData()

            
        }
        
        let onlyCheckCurrentUsingDevice = UIAlertAction.init(title: NSLocalizedString(LOCALIZABLE_STRING_ONLY_CHECK_CURRENT_USING_DEVICE, comment: ""), style: .default) { (UIAlertAction) in
            
//            self.notificationType = .current
//            
//            self.notificationTableView.mj_header.beginRefreshing()
            
            self.alertArray.removeAll()
            
            if self.backupAlertArray.count > 0 {
                
                self.sortBackupAlertArray()
                
                for h in self.backupAlertArray {
                    
                    if h?.AlarmType != 48 && h?.AlarmType != 28 && h?.AlarmType != 21 && h?.SerialNumber == UserModel.userModel.selectedDeviceSerialNumber {
                        
                        self.alertArray.append(h)
                        
                    }
                    
                }
                
            }
            
            self.notificationTableView.reloadData()

            
        }
        
        let cancelAction = UIAlertAction.init(title: NSLocalizedString(LOCALIZABLE_STRING_CANCEL, comment: ""), style: .cancel, handler: nil)
        
        alertController.addAction(onlyCheckWakeUp)
        alertController.addAction(checkAllNotification)
        alertController.addAction(onlyCheckCurrentUsingDevice)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)
        
        
    }
    
    // MARK: - 选择日期
    @IBAction func selectDate(_ sender: Any) {
        
        datePicker = UIDatePicker.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200, width: STATIC_VALUE_SCREEN_WIDTH, height: 200))
        
        datePicker?.backgroundColor = UIColor.white
        
        datePicker?.datePickerMode = .date
        
        datePicker?.date = selectDate
        
        
        
        let toolBar = UIToolbar.init(frame: CGRect(x: 0, y: STATIC_VALUE_SCREEN_HEIGHT - 200 - 30, width: STATIC_VALUE_SCREEN_WIDTH, height: 30))
        
        toolBar.barStyle = .default
        
        let fixedBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        
        let confirmBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CONFIRM, comment: ""), style: .done, target: self, action: #selector(datePickFinish))
        
        let cancelBarButtonItem = UIBarButtonItem.init(title: NSLocalizedString(LOCALIZABLE_STRING_CANCEL, comment: ""), style: .done, target: self, action: #selector(datePickCancel))
        
        toolBar.setItems([fixedBarButtonItem,cancelBarButtonItem,confirmBarButtonItem], animated: true)
        
        
        
        
        let window = UIApplication.shared.keyWindow
        
        blackBackgroudView = UIView.init(frame: (window?.bounds)!)
        
        blackBackgroudView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        
        blackBackgroudView?.addSubview(datePicker!)
        
        blackBackgroudView?.addSubview(toolBar)
        
        window?.addSubview(blackBackgroudView!)
        
    }
    
    // MARK: - datePickerCancel
    func datePickCancel() {
        
        blackBackgroudView?.removeFromSuperview()
        
    }
    
    // MARK: - datePicker回调
    func datePickFinish() {
        
        let date = datePicker?.date
        
        if date != nil {
            selectDate = date!
        }

        notificationTableView.mj_header.beginRefreshing()
        
        blackBackgroudView?.removeFromSuperview()
        
        
    }
    
    // MARK: - tableView delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if alertArray.count == 0 {
            
            self.view.addSubview(noDataLabel)
            
        }else {
            
            noDataLabel.removeFromSuperview()
            
        }
        
        return alertArray.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell:NotificationCenterTableViewCell
        
        if (tableView.dequeueReusableCell(withIdentifier: "NotificationCenterTableViewCell") == nil) {
            
            cell = NotificationCenterTableViewCell.init(style: .default, reuseIdentifier: "NotificationCenterTableViewCell")
            
            
        }else {
            
            cell = tableView.dequeueReusableCell(withIdentifier: "NotificationCenterTableViewCell") as! NotificationCenterTableViewCell
            
        }
        
        cell.selectionStyle = .none
        
        let h = alertArray[indexPath.row]
        
        //time 
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = STATIC_VALUE_DATE_FORMATTER + " " + STATIC_VALUE_TIME_FORMATTER
        let date = Date.init(timeIntervalSince1970: (h?.EventTime?.doubleValue)!)
        let timeString = dateFormatter.string(from: date)
        
        //displayName
        var displayName = h?.SerialNumber
        for dict in UserModel.userModel.devicesByAccountArray! {
            
            let devicesByAccount = DevicesByAccount.mj_object(withKeyValues: dict)
            
            if h?.SerialNumber == devicesByAccount?.SerialNumber {
                
                displayName = devicesByAccount?.DisplayName
                
            }
            
        }
        
        //alarmType
        var alarmTypeString = "\(h?.AlarmType?.intValue ?? 255)"
        
        let path = Bundle.main.path(forResource: "AlarmTypePlist", ofType: "plist")
        
        let typeDict = NSDictionary.init(contentsOfFile: path ?? "")
        
        if typeDict != nil {
            
            let s = typeDict?.value(forKey: "\(h?.AlarmType?.intValue ?? 255)")
            
            alarmTypeString = s as! String
            
            if h?.AlarmType == 14 || h?.AlarmType == 15 {
                
                var ss = h?.Message
                
                if h?.Message != nil {
                    
                    if !(h?.Message?.isEmpty)! {
                        
                        if h?.AlarmType == 15 {
                            let range = ss?.range(of: "has entered fence ")
                            
                            ss = h?.Message?.substring(from: (range?.upperBound)!)
                            
                        }else if h?.AlarmType == 14 {
                            
                            let range = ss?.range(of: "has exited fence ")
                            
                            ss = h?.Message?.substring(from: (range?.upperBound)!)
                            
                        }
                        
                        
                        
                        if ss != nil {
                            
                            alarmTypeString = alarmTypeString + " - " + ss!
                            
                        }
                        
                    }
                    
                }
                
                
                
            }
            
        }
        
        cell.setUpCell(alarmTime: timeString, serialNumber: h?.SerialNumber, displayName: displayName, alarmType: alarmTypeString)
        
        
        
        return cell
        
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
